document.addEventListener('DOMContentLoaded', function() {
    const chatBox = document.getElementById('chatBox');
    const userInput = document.getElementById('userInput');
    const sendBtn = document.getElementById('sendBtn');

    // Function to send message when button is clicked
    sendBtn.addEventListener('click', sendMessage);

    // Function to send message when Enter key is pressed (without Shift)
    userInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();  // Prevent newline
            sendMessage();
        }
    });

    function sendMessage() {
        const message = userInput.value.trim();
        
        // Don't send empty messages
        if (message === '') return;

        // Add user message to chat
        addMessageToChat(message, 'user');
        
        // Clear input field
        userInput.value = '';

        // Create a placeholder for the bot's response
        const botMessageId = addBotTypingIndicator();
        
        // Make API call to the backend using streaming
        fetchStreamingAIResponse(message, botMessageId);
        // fetchAIResponse(message)
    }

    function addMessageToChat(message, sender) {
        const messageDiv = document.createElement('div');
        messageDiv.classList.add('message', sender);

        const avatar = document.createElement('div');
        avatar.classList.add('avatar');
        
        const icon = document.createElement('i');
        icon.classList.add('fas');
        
        // Different icon based on sender
        if (sender === 'user') {
            icon.classList.add('fa-user');
        } else {
            icon.classList.add('fa-user-md');
        }
        
        avatar.appendChild(icon);
        messageDiv.appendChild(avatar);

        const content = document.createElement('div');
        content.classList.add('content');
        
        // 修改这里：对于AI回复，使用innerHTML渲染HTML格式，对于用户消息使用textContent
        if (sender === 'bot') {
            content.innerHTML = message;
        } else {
            const text = document.createElement('p');
            text.textContent = message;
            content.appendChild(text);
        }
        
        messageDiv.appendChild(content);
        chatBox.appendChild(messageDiv);
        
        // Scroll to the bottom
        chatBox.scrollTop = chatBox.scrollHeight;

        // Return the message element so it can be updated later
        return messageDiv;
    }

    function addBotTypingIndicator() {
        const messageDiv = document.createElement('div');
        messageDiv.classList.add('message', 'bot', 'bot-response');
        
        const avatar = document.createElement('div');
        avatar.classList.add('avatar');
        
        const icon = document.createElement('i');
        icon.classList.add('fas', 'fa-user-md');
        
        avatar.appendChild(icon);
        messageDiv.appendChild(avatar);

        const content = document.createElement('div');
        content.classList.add('content');
        
        const typing = document.createElement('div');
        typing.classList.add('typing');
        
        // Add three dots for the typing animation
        for (let i = 0; i < 3; i++) {
            const dot = document.createElement('span');
            typing.appendChild(dot);
        }
        
        content.appendChild(typing);
        messageDiv.appendChild(content);

        chatBox.appendChild(messageDiv);
        
        // Scroll to the bottom
        chatBox.scrollTop = chatBox.scrollHeight;

        return messageDiv;
    }

    function updateBotResponseContent(botMessage, text) {
        const content = botMessage.querySelector('.content');
        
        // 格式化文本，处理markdown风格的内容
        const formattedText = formatResponse(text);
        
        // Replace typing indicator with formatted text
        content.innerHTML = formattedText;
        
        // Scroll to the bottom
        chatBox.scrollTop = chatBox.scrollHeight;
    }

    // 新增：格式化响应内容的函数
    function formatResponse(text) {
        // 如果文本中包含markdown格式的标题，进行HTML格式化
        let formatted = text;
        
        // 处理标题 (## 和 ### 格式)
        formatted = formatted.replace(/### (.*?)$/gm, '<h3>$1</h3>');
        formatted = formatted.replace(/## (.*?)$/gm, '<h2>$1</h2>');
        
        // 处理粗体文本 (**text**)
        formatted = formatted.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
        
        // 处理列表项 (- item)
        formatted = formatted.replace(/- (.*?)$/gm, '<li>$1</li>');
        
        // 将连续的列表项包装在ul标签中
        const listRegex = /(<li>.*?<\/li>)\n(<li>.*?<\/li>)/gs;
        while (listRegex.test(formatted)) {
            formatted = formatted.replace(listRegex, '$1$2');
        }
        
        formatted = formatted.replace(/(<li>.*?<\/li>)+/g, '<ul>$&</ul>');
        
        // 处理段落 (多行文本)
        formatted = formatted.replace(/^(?!<[hu][l\d]|<li|<p)(.*?)$/gm, '<p>$1</p>');
        
        // 移除空段落
        formatted = formatted.replace(/<p>\s*<\/p>/g, '');
        
        // 处理换行，确保段落间有适当间隔
        formatted = formatted.replace(/<\/h[23]>\s*<p>/g, '</h$1><p>');
        
        return formatted;
    }

    function fetchStreamingAIResponse(userMessage, botMessageElement) {
        // 使用fetch API执行POST请求
        // console.log('开始请求API:', userMessage);
        fetch('/ai-doctor/api/stream-consult', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ query: userMessage })
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`网络响应不佳 (${response.status}: ${response.statusText})`);
            }
            
            // 确认响应是否支持流
            if (!response.body) {
                throw new Error('响应不支持流式传输');
            }
            
            // 获取响应的reader流
            const reader = response.body.getReader();
            let accumulatedText = '';
            let buffer = ''; // 用于存储不完整的消息片段

            // 处理流式数据
            const processStream = ({ done, value }) => {
                // console.log('流读取状态:', done, '数据长度:', value ? value.length : 0);
                
                if (done) {
                    // console.log('流读取完成');
                    return;
                }
                
                // 解码接收到的数据块并添加到缓冲区
                buffer += new TextDecoder().decode(value);
                // console.log('当前缓冲区:', buffer);
                
                // 处理完整的SSE消息
                // SSE消息格式为: event:message\ndata:{JSON}\n\n
                // 查找并处理所有完整的消息
                let position;
                while ((position = buffer.indexOf('\n\n')) !== -1) {
                    const message = buffer.substring(0, position);
                    buffer = buffer.substring(position + 2);
                    
                    // console.log('处理完整SSE消息:', message);
                    
                    // 解析SSE消息
                    const eventMatch = message.match(/^event:([^\n]+)\ndata:(.+)$/s);
                    if (eventMatch) {
                        const eventType = eventMatch[1].trim();
                        const dataContent = eventMatch[2].trim();
                        
                        // console.log('SSE事件类型:', eventType);
                        // console.log('SSE数据内容:', dataContent);
                        
                        if (eventType === 'message') {
                            try {
                                const eventData = JSON.parse(dataContent);
                                // console.log('解析的JSON数据:', eventData);
                                
                                // 累积响应文本
                                accumulatedText += eventData.content || '';
                                
                                // 更新聊天界面 - 实时格式化内容
                                updateBotResponseContent(botMessageElement, accumulatedText);
                                
                                // 如果收到完成信号
                                if (eventData.done) {
                                    // console.log('收到完成信号');
                                    // 最终格式化响应
                                    updateBotResponseContent(botMessageElement, accumulatedText);
                                    return;
                                }
                            } catch (e) {
                                console.error('解析事件数据失败:', e, '原始数据:', dataContent);
                            }
                        }
                    } else {
                        console.log('不符合SSE格式的消息:', message);
                    }
                }
                
                // 继续读取流
                return reader.read().then(processStream).catch(err => {
                    console.error('读取流时出错:', err);
                    updateBotResponseContent(botMessageElement, accumulatedText + '<br><br>[读取中断: ' + err.message + ']');
                });
            };
            
            // 开始读取流
            // console.log('开始读取流');
            return reader.read()
                .then(processStream)
                .catch(err => {
                    console.error('初始读取流出错:', err);
                    updateBotResponseContent(botMessageElement, '解析响应时出错: ' + err.message);
                });
        })
        .catch(error => {
            console.error('流式API调用错误:', error);
            updateBotResponseContent(botMessageElement, '抱歉，我暂时无法回应您的问题。请稍后再试。错误: ' + error.message);
        });
    }

    function fetchAIResponse(userMessage) {
        // Make API call to the backend
        fetch('/ai-doctor/api/consult', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ query: userMessage })
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不佳');
            }
            return response.json();
        })
        .then(data => {
            // Remove loading indicator
            removeLoadingIndicator();
            
            // Add AI response to chat
            addMessageToChat(data.response, 'bot');
        })
        .catch(error => {
            // Remove loading indicator
            removeLoadingIndicator();
            
            // Show error message
            addMessageToChat('抱歉，我暂时无法回应您的问题。请稍后再试。错误: ' + error.message, 'bot');
            console.error('API调用错误:', error);
        });
    }

    function removeLoadingIndicator() {
        const loadingMessage = document.querySelector('.loading-message');
        if (loadingMessage) {
            loadingMessage.remove();
        }
    }
});
